import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {CustomValidators} from "ng2-validation";
import {AppService} from "../../../services/app.service";
import {Md5} from "ts-md5";
import {ResDataModel} from "../../../models/res-data-model";
import {IdCardValidator} from "../../../validators/id-card.derective";

/**
 * Generated class for the RegisterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  mail:string;
  public myForm:FormGroup;//form表单中的值

  validation_messages = {
    'identifyingCode': '请输入六位验证码',
    'userCode':'账号名不能为空',
    'nickName': '昵称不能为空',
    'userName': '真实姓名不能为空',
    'idCard':'身份证号码格式不正确',
    'mobileNumber': '手机号码格式不正确',
    'initPass':'密码不能为空，且至少为六位数',
    'surePass':'两次密码输入不一致',
  };

  constructor(public navCtrl: NavController,
              public formBuilder:FormBuilder,
              public navParams: NavParams,
              private appService:AppService) {
    this.mail = this.navParams.get("mail");
    let initPass = new FormControl('', [Validators.required,Validators.minLength(6)]);
    this.myForm=this.formBuilder.group({
      identifyingCode:["",[Validators.required,Validators.minLength(6),Validators.maxLength(6)]],
      userCode:["",Validators.required],
      nickName:["",Validators.required],
      userName:["",Validators.required],
      initPass,
      surePass:["",CustomValidators.equalTo(initPass)],
      gender:[""],
      idCard:["",[Validators.required,IdCardValidator.idCard]],
      mobileNumber:["",[CustomValidators.phone('CN'),CustomValidators.rangeLength([11,11])]],
    });
  }

  ionViewDidLoad() {
  }

  /**
   * 注册
   */
  register(){
    event.preventDefault();
    let formModel = this.myForm.value;
    if(this.appService.validate(this.myForm,this.validation_messages)){
      let postData = {
        userInfo:{
          dlzh:formModel.userCode,
          identifyingCode:formModel.identifyingCode,
          nickName:formModel.nickName,
          userName:formModel.userName,
          xb:formModel.gender,
          sfzh:formModel.idCard,
          sjhm:formModel.mobileNumber,
          mail:this.mail,
          password:Md5.hashStr(formModel.initPass)
        }
      }
      this.appService.httpPost('AppUserCtrl_register',postData,null,(res:ResDataModel)=>{
        let datas = res.datas;
        console.log(datas);
        if(datas[1].value == "success"){
          //注册成功跳转登陆页
          this.appService.smallToast('注册成功','success');
          this.navCtrl.popToRoot();
        }
      },true);
    }
  }

}
